$(function(){

    var logopath = [];

    $("input[name=imgs]").change(function(){
        //将表单数据提交给后台
        //1、获取表单的dom对象
        var formdom = $("#from-thrum")[0];
        //2、创建表单数据对象
        var formdata = new FormData(formdom);
        //3、发送ajax请求
        $.ajax({
            url: "/api/upload-img",
            method: "POST",
            data: formdata,
            contentType: false,//数据编码格式不用jquery方式
            processData: false,//传输的数据，不被jquery封装
            success: function(data){
                if(data.status == 0){
                    for(var i=0;i<data.data.imgpath.length;i++){
                        $(".imgthume")[i].src = "/"+data.data.imgpath[i];
                        logopath.push("/"+data.data.imgpath[i]);
                    }
                }else if(data.status == 1){
                    myalert(data.message)
                }
            },
            error: function(err){
                console.log(err)
            }
        })
    });

    $("#form-button").click(function(){
        if(!$("#goodsname").val()){
            myalert("商品名不能为空");
        }else if(!$("#goodsprice").val()){
            myalert("商品价格不能为空");
        }else if(!$("#goodsdes").val()){
            myalert("商品描述不能为空");
        }else if(logopath.length == 0){
            myalert("商品图片不能为空");
        }else if($("#goodsname").val()&&$("#goodsprice").val()&&$("#goodsprice").val()&&logopath){
            $.ajax({
                url: "/api/addgoods",
                method: "POST",
                data: {
                    goodsname: $("#goodsname").val(),
                    price: $("#goodsprice").val(),
                    des: $("#goodsdes").val(),
                    thumb: logopath,
                },
                success: function(data){
                    location.href = "/goodslist"
                },
                error: function(error){
                    console.log(error)
                }
            })
        }
    })
})


function myalert(str){
    if(document.getElementsByClassName("my-alert").length == 0){
        new Promise(function(resolve,reject){
            var odiv = document.createElement("div");
            odiv.className = "my-alert";
            odiv.innerHTML = str;
            document.body.appendChild(odiv);
            resolve(odiv)
        }).then(function(odiv){
            var outtimer = setTimeout(function(){
                odiv.remove();
                clearTimeout(outtimer);
            },1000);
        })
    }
}